package com.jiaai.cloud.api;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.jiaai.cloud.base.exception.LoginException;
import com.jiaai.cloud.base.exception.ServiceException;
import com.jiaai.cloud.base.page.FrontPage;
import com.jiaai.cloud.base.util.RestResult;
import com.jiaai.cloud.base.util.RestResultGenerator;
import com.jiaai.cloud.gift.entity.TLiveGift;
import com.jiaai.cloud.gift.entity.TLiveGiftDetail;
import com.jiaai.cloud.gift.service.ITLiveGiftDetailService;
import com.jiaai.cloud.gift.service.ITLiveGiftService;
import com.jiaai.cloud.gift.service.ITLiveGiftTypeService;
import com.jiaai.cloud.live.service.ITLiveBroadcastService;
import com.jiaai.cloud.user.entity.TUserWallet;
import com.jiaai.cloud.user.service.ITUserWalletService;
import com.jiaai.cloud.utils.HttpHeaderUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.awt.peer.FontPeer;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  礼物api接口
 * </p>
 *
 * @author 佳爱网络科技
 * @version V1.0
 * @title GiftAPI
 * @since 2017/8/1
 */
@RequestMapping("/api/v1")
@RestController
public class GiftAPI {

    private  static  final Logger log= LoggerFactory.getLogger(GiftAPI.class);
    @Autowired
    private ITLiveGiftService giftService;
    @Autowired
    private ITLiveGiftDetailService giftDetailService;
    @Autowired
    private ITLiveBroadcastService broadcastService;

    @Autowired
    private ITUserWalletService userWalletService;
    @Autowired
    private ITLiveGiftTypeService giftTypeService;

    /**
     * 返回直播模块的礼物列表
     * @return
     */
//    @GetMapping("/live/gift/list")
//    public Object findLiveGiftByAll(){
//
//        return RestResultGenerator.genSuccessResult(giftTypeService.joinGiftByAll());
//    }

    /**
     * 返回聊天室的礼物列表
     * @return
     */
    @GetMapping("/chatroom/gift/list")
    public  Object findChatRoomGiftByAll(){
        return RestResultGenerator.genSuccessResult(giftService.selectList(new EntityWrapper().eq("type",1)));
    }

    /**
     * 赔送礼物
     * @param
     * @return
     */
    @PostMapping("/live/gift/give")
    public  Object sendGiftForLivt(@RequestBody TLiveGiftDetail giftDetail)throws Exception{

        String userId="";
        try {

            userId=HttpHeaderUtils.getUserId();
        }catch (Exception e){
            throw  new ServiceException("未登录");
        }
        if(StringUtils.isEmpty(giftDetail.getAnchorId())|| StringUtils.isEmpty(giftDetail.getBroadcastId())){
            throw  new ServiceException("参数错误");
        }
        TLiveGift gift=giftService.selectById(giftDetail.getGiftId());
        if(gift==null){
            throw  new ServiceException("礼物不存在");
        }

        TUserWallet userWallet=userWalletService.selectOne(new EntityWrapper().eq("userId",userId));
        if(userWallet.getMoney().compareTo(BigDecimal.valueOf(gift.getGlod()))==-1){
            throw  new ServiceException("佘额不足,请先充值!");
        }
        if(gift.getCommission()!=null){//如果存在拥金则更新主播钱包
            TUserWallet anchorWallet=userWalletService.findByAnchorId(giftDetail.getAnchorId());
            if(anchorWallet==null){
                throw  new ServiceException("系统错误");
            }
            anchorWallet.setMoney(anchorWallet.getMoney().add(BigDecimal.valueOf(gift.getGlod()*gift.getCommission())));
            try{
                userWalletService.insertOrUpdate(anchorWallet);
            }catch (Exception e){
                 log.error("更新主播钱包失败");
            }

        }
        try{
            userWallet.setMoney(userWallet.getMoney().subtract(BigDecimal.valueOf(gift.getGlod())));
            userWalletService.insertOrUpdate(userWallet);
            giftDetail.setSendFrom(userId);
            giftDetail.setGlod(gift.getGlod());
            giftDetail.setSendTime(new Date());
            giftDetailService.insert(giftDetail);
        }catch (Exception e){
            throw new ServiceException("服务器异常",e.getLocalizedMessage());
        }
        return RestResultGenerator.genSuccessResult();
    }

    /**
     * 获取直播间礼物赠送记录
     * @param page
     * @param id
     * @return
     */
   @GetMapping("/live/giftdetail/list/{id}")
   public  Object getBroadcastGiveDetail(FrontPage page, @PathVariable("id") String id)throws  ServiceException{
         return RestResultGenerator.genSuccessResult(giftDetailService.joinFullyByBroadcastId(page.getPagePlus(),id));
    }




}
